package org.micro.frame.service.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.micro.frame.service.Constants;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

/**
 * The Micro OncePerRequestFilter
 *
 * @author lry
 */
@Slf4j
public class MicroOncePerRequestFilter extends OncePerRequestFilter {

    private final AtomicLong REQUEST_ID_COUNTER = new AtomicLong(10000);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 创建请求ID
        String requestId = String.valueOf(REQUEST_ID_COUNTER.incrementAndGet());

        // 校验交易ID,为空则生成ID
        String traceId = request.getHeader(Constants.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }

        try {
            // 添加MDC参数
            Map<String, String> contextMap = new HashMap<>(16);
            contextMap.put(Constants.TRACE_ID, traceId);
            contextMap.put(Constants.REQUEST_ID, requestId);
            MDC.setContextMap(contextMap);

            log.debug("The input server.");

            // 设置全局响应头
            response.setHeader(Constants.TRACE_ID, traceId);
            response.setHeader(Constants.REQUEST_ID, requestId);
            response.setCharacterEncoding(Constants.CHARACTER_ENCODING);

            filterChain.doFilter(request, response);
        } finally {
            // 清理MDC参数
            MDC.clear();
        }
    }

}